import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(), // 从缓存中读取初始值
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  resetState: (state) => {
    Object.assign(state, getDefaultState())
  },
  // 修改token
  setToken: (state, token) => {
    // 只是设置了Vuex 中的数据
    state.token = token
    // 需要将Vuex 中的数据同步到缓存中
    setToken(token)
  },
  removeToken: (state) => {
    // 设置Vuex中的token 为null
    state.token = null
    // 同步删除缓存中的token
    removeToken()
  },
  //
  setName: (state, name) => {
    state.name = name
  },
  //
  setAvatar: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // user login 用户登录接口
  // 第一个参数: context 上下文，第二个参数：传入的参数
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        // 触发mutations 里面的setToken 方法
        // 也可以这样写, context.commit('setToken',data.token)
        commit('setToken', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { name, avatar } = data

        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

// 进行导出
export default {
  namespaced: true, // 开启命名空间
  state,
  mutations,
  actions
}

